package com.mall.pay.services;

import com.mall.pay.PayCoreService;
import com.mall.pay.constants.PayResultEnum;
import com.mall.pay.dal.entitys.Payment;
import com.mall.pay.dal.persistence.PaymentMapper;
import com.mall.pay.dto.CashierPayRequest;
import com.mall.pay.dto.PaymentRequest;
import com.mall.pay.dto.alipay.AlipayQueryRetResponse;
import com.mall.pay.dto.alipay.AlipaymentResponse;
import com.mall.pay.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

@Service
@Slf4j
public class PayCoreServiceImpl implements PayCoreService {

    @Autowired
    private PayHelper payHelper;
    @Autowired
    private PaymentMapper paymentMapper;

    @Override
    public AlipaymentResponse aliPay(CashierPayRequest cashierPayRequest) {

        AlipaymentResponse response = new AlipaymentResponse();
        PaymentRequest paymentRequest = new PaymentRequest();
        try {
            // 1.  使用支付宝sdk的功能去请求，支付二维码
            String qrFileName = payHelper.test_trade_precreate(paymentRequest);

            if (qrFileName == null) {
                // 请求支付二维码失败
                response.setCode(PayResultEnum.PAY_FAIL.getCode());
                response.setMsg(PayResultEnum.PAY_FAIL.getDesc());
                log.error("PayCoreServiceImpl.aliPay occur Exception : " + "请求二维码失败，未返回二维码");
                return response;
            } else {
                // 否则，请求到支付二维码
                // 2.  在本地插入tb_payment，插入一条本次订单的一条支付记录
                insertPayment(cashierPayRequest);
                response.setQrCode(qrFileName);
            }
        } catch (Exception e) {
            log.error("PayCoreServiceImpl.aliPay occur Exception : " + e.getMessage());
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }

    @Override
    public AlipayQueryRetResponse queryAlipayRet(CashierPayRequest cashierPayRequest) {
        PaymentRequest paymentRequest = new PaymentRequest();
        boolean isSuccess = payHelper.test_trade_query(paymentRequest);

        if (isSuccess) {
          // 支付成功
            // 1. 修改本订单对应的支付记录： 修改为支付成功
            // 2. 修改订单状态，为已支付状态

            // 3. 修改库存，将订单中商品对应的库存，锁定库存清零
            // 4.  修改订单商品条目，对应的库存状态：3 成功扣减库存
        } else {
            // 没有成功支付
            // 修改本订单对应的支付记录： 修改为支付失败
        }
        return null;
    }

    private void insertPayment(CashierPayRequest request) {
        Payment payment = new Payment();

    }
}
